<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Article extends Model
{
    protected $fillable = [
        'title', 'author', 'content_markdown', 'content_html', 'category_id', 'intro',
        'img', 'seo_title', 'seo_keywords', 'seo_description', 'weight', 'is_top',
        'is_recommend', 'is_hot', 'state', 'tag_id',
    ];

    protected $appends = ['category_name'];

    /**
     * 关联tags表模型。多对多
     * @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
     */
    public function tags()
    {
        return $this->belongsToMany('App\Models\Tag')->withTimestamps();
    }

    /**
     * 关联到文章分类模型，一对多。
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function articleCategory()
    {
        return $this->belongsTo('App\Models\ArticleCategory', 'category_id');
    }

    /**
     * 添加关联属性
     *
     * @return string
     */
    public function getCategoryNameAttribute()
    {
        return optional($this->articleCategory)->name ?? '';
    }
}
